package com.kele.sms.service;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
@RabbitListener(queues = {"sms"},concurrency = "2")
public class MQService {

    @Value("${sms.accessKeyId}")
    private String accessKeyId;

    @Value("${sms.accessSecret}")
    private String accessSecret;

    @RabbitHandler
    public void testRevMsg(Map<String,String> map, Message message, Channel channel) throws IOException {

        System.out.println(map);
        System.out.println("执行完业务逻辑");

        String signName = map.get("signName");
        String templateCode = map.get("templateCode");
        String mobile = map.get("mobile");
        String templateParam = map.get("templateParam");

        sendSMS(signName,templateCode,mobile,templateParam);

        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        System.out.println(deliveryTag);

        channel.basicAck(deliveryTag,false);//ACK
    }

    public void sendSMS(String signName,
                        String templateCode,
                        String mobile,
                        String templateParam) {
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-hangzhou",
                accessKeyId,
                accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", signName/*"思远"*/);
        request.putQueryParameter("TemplateCode", templateCode/*"SMS_158845051"*/);

        request.putQueryParameter("TemplateParam", templateParam);//{\"code\":\"1234353\"}"
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}
